//
//  MyStoreController.swift
//  hello
//
//  Created by yafei li on 2025/10/9.
//

import AppStoreServerLibrary
import Vapor

// Store验证请求结构
struct StoreVerificationRequest: Content {
    let transactionId: String
    // 可以根据需要添加其他字段，如receiptData、productId等
}

struct StoreController: RouteCollection {
  func boot(routes: any Vapor.RoutesBuilder) throws {
    let storeRoutes = routes.grouped("api", "store")
    storeRoutes.post("verify", use: verifyStore)
  }
 
  func verifyStore(req: Request) async throws -> ApiResponse<EmptyContent> {
    // 从请求中获取需要验证的数据（例如收据或订阅信息）
    guard let requestBody = try? req.content.decode(StoreVerificationRequest.self) else {
        throw Abort(.badRequest, reason: "Invalid request body")
    }
    
    // 使用AppStore Server Library进行验证
    let client = try AppStoreServerAPIClient(
        signingKey: "YOUR_PRIVATE_KEY", // 替换为真实的私钥
        keyId: "YOUR_KEY_ID",
        issuerId: "YOUR_ISSUER_ID",
        bundleId: "YOUR_BUNDLE_ID",
        environment: .production
    )
    
    do {
        // 创建交易历史请求
        let transactionHistoryRequest = TransactionHistoryRequest()
        // 可以根据需要设置过滤条件，例如：
        // transactionHistoryRequest.productIds = ["your_product_id"]
        
        // 验证交易或订阅状态 - 使用正确的返回类型
        let response =  await client.getTransactionHistory(
            transactionId: requestBody.transactionId,
            revision: "", // 首次查询使用nil
            transactionHistoryRequest: transactionHistoryRequest,
            version: GetTransactionHistoryVersion.v2
        )
        
        switch response{
           case .success(let transactionResponse):
            // 处理成功的验证结果
            print("Transaction verified: \(transactionResponse)")
            return ApiResponse<EmptyContent>(code: 200, message: "Transaction verified successfully", data: nil)
           case .failure(let statusCode, let  rawApiError, let apiError, let  errorMessage, let causedBy):
            // 处理验证失败的情况
            print("Transaction verification failed: \(String(describing: errorMessage))")
            throw Abort(.badRequest, reason: "Transaction verification failed: \(String(describing: errorMessage))")
        }
      
    } catch {
        throw Abort(.internalServerError, reason: "Store verification error: \(error)")
    }
  }
}